package com.caifu.controller;

import com.caifu.bean.ResultUtil;
import com.caifu.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * springboot全局异常处理
 *
 * @author tww
 * ClassName: GlobalExceptionHandler.java、
 * createTime: 2021年03月04日 10:33:04
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = CustomException.class)
    @ResponseBody
    public Object CustomExceptionHandler(CustomException e) {
        logger.error("发生业务异常！原因是：{}", e.getResultEnum().getMsg());
        return ResultUtil.error(e.getResultEnum().getCode(), e.getResultEnum().getMsg());
    }


    /**
     * 处理空指针的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public Object exceptionHandler(NullPointerException e) {
        logger.error("发生空指针异常！原因是:", e);
        return ResultUtil.error(500, "空指针异常");
    }

    /**
     * 处理其他异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object exceptionHandler(Exception e) {
        logger.error("未知异常！原因是:", e);
        return ResultUtil.error();
    }

}
